package com.picturewatermark.core;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.NoSuchElementException;

import org.apache.log4j.Logger;

import com.picturewatermark.exception.WatermarkSizeException;
import com.picturewatermark.util.BufferedImageConverter;

public class PictureWatermarker {
	private final static Logger LOG = Logger
			.getLogger(PictureWatermarker.class);

	private PictureWatermarker() {

	}

	public static Image watermark(final Image picture, final Image watermark,
			final int x_offset, final int y_offset) {
		LOG.debug("Picture: " + picture + "\t" + "Watermark: " + watermark
				+ "\t" + "x_offset: " + x_offset + "\t" + "y_offset: "
				+ y_offset);

		if (x_offset < 0 || y_offset < 0) {
			throw new IllegalArgumentException(
					"Offset must be a positive integer");
		}

		if (picture == null) {
			throw new NullPointerException("Image picture is null");
		}

		if (watermark == null) {
			return picture;
		}

		int pictureWidth = picture.getWidth(null);
		int pictureHeight = picture.getHeight(null);
		int watermarkWidth = watermark.getWidth(null);
		int watermarkHeight = watermark.getHeight(null);

		if (pictureWidth < 0 || pictureHeight < 0 || watermarkWidth < 0
				|| watermarkHeight < 0) {
			throw new NoSuchElementException("Picture cannot be empty");
		}

		if (watermarkWidth == 0 || watermarkHeight == 0) {
			return picture;
		}

		if (watermarkWidth > pictureWidth || watermarkHeight > pictureHeight) {
			throw new WatermarkSizeException("Watermark is too big for picture");
		}

		BufferedImage bpicture = BufferedImageConverter
				.getBufferedImage(picture);
		Graphics bpG = bpicture.getGraphics();
		boolean imageDrawn = false;
		do {
			imageDrawn = bpG.drawImage(watermark, x_offset, y_offset, null);
		} while (imageDrawn == false);
		bpG.dispose();

		return bpicture;
	}
}
